# 检测企业微信是否运行
import psutil
import os
import win32gui
import win32con
import win32api
import time
import pyautogui
from path_manager import path_manager
# 检查企业微信是否运行
def check_wechat():
    """检查企业微信进程是否正在运行"""
    try:
        wechat_processes = []
        for proc in psutil.process_iter(['pid', 'name']):
            try:
                if proc.info['name'] == 'WXWork.exe':
                    wechat_processes.append(proc.info['pid'])
            except (psutil.NoSuchProcess, psutil.AccessDenied, AttributeError):
                # 忽略已结束、无权限或信息不完整的进程
                continue

        if wechat_processes:
            print(f"找到 {len(wechat_processes)} 个企业微信进程: {wechat_processes}")
            return True
        else:
            print("未找到企业微信进程")
            return False

    except ImportError:
        print("错误：未安装psutil库，无法检查进程状态")
        return False
    except Exception as e:
        print(f"检查企业微信进程时出错: {e}")
        return False

  
# 启动企业微信
def start_wechat():
    """启动企业微信，并验证启动是否成功"""
    path = path_manager.get_wechat_path()
    if not path:
        print("未找到企业微信可执行文件，请检查配置文件中的路径设置")
        return False

    print(f"正在启动企业微信: {path}")

    try:
        # 记录启动前的进程状态
        initial_process_count = len([p for p in psutil.process_iter(['pid', 'name']) if p.info['name'] == 'WXWork.exe'])

        # 使用subprocess而不是os.system来获得更好的控制
        import subprocess
        result = subprocess.run(['start', path], shell=True, capture_output=False, timeout=10)

        if result.returncode != 0:
            print(f"警告：启动命令返回非零值: {result.returncode}")

        # 等待启动完成
        print("等待企业微信启动...")
        start_time = time.time()
        timeout = 15  # 最长等待15秒

        while time.time() - start_time < timeout:
            try:
                current_process_count = len([p for p in psutil.process_iter(['pid', 'name']) if p.info['name'] == 'WXWork.exe'])
                if current_process_count > initial_process_count:
                    print("企业微信进程启动成功")
                    return True
            except (psutil.NoSuchProcess, psutil.AccessDenied):
                pass  # 忽略进程访问错误

            time.sleep(0.5)  # 每0.5秒检查一次

        print("警告：启动超时，企业微信进程可能未成功启动")
        return False

    except subprocess.TimeoutExpired:
        print("警告：启动命令执行超时")
        return False
    except Exception as e:
        print(f"启动企业微信时出错: {e}")
        return False


# 检测和清理重复的企业微信窗口
def cleanup_duplicate_wechat_windows():
    """
    检测并清理重复的企业微信窗口，避免黑屏窗口
    修改：只有当真正发现多个窗口时才进行清理，避免误杀正常窗口
    """
    try:
        # 查找所有企业微信窗口
        def find_wechat_windows(hwnd, windows):
            window_text = win32gui.GetWindowText(hwnd)
            if ("企业微信" in window_text or "WXWork" in window_text) and "自动化工具" not in window_text:
                if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd):
                    try:
                        window_placement = win32gui.GetWindowPlacement(hwnd)
                        current_state = window_placement[1]
                        # 获取窗口位置和大小
                        rect = win32gui.GetWindowRect(hwnd)
                        windows.append((hwnd, window_text, current_state, rect))
                    except Exception as e:
                        print(f"获取窗口信息失败: {e}")
                        windows.append((hwnd, window_text, None, None))
            return True
        
        windows = []
        win32gui.EnumWindows(find_wechat_windows, windows)
        
        # 只有当真正发现多个窗口时才进行清理
        if len(windows) <= 1:
            print("未发现重复的企业微信窗口")
            return True
        
        print(f"发现 {len(windows)} 个企业微信窗口，开始分析...")
        
        # 按窗口状态分类（用于调试信息）
        minimized_count = len([w for w in windows if w[2] == win32con.SW_SHOWMINIMIZED])
        normal_count = len([w for w in windows if w[2] == win32con.SW_SHOWNORMAL])
        maximized_count = len([w for w in windows if w[2] == win32con.SW_SHOWMAXIMIZED])
        
        # 检查是否有真正的重复窗口（相同状态且位置相近）
        duplicate_groups = []
        processed_windows = set()
        
        for i, window1 in enumerate(windows):
            if i in processed_windows:
                continue
                
            group = [window1]
            processed_windows.add(i)
            
            for j, window2 in enumerate(windows[i+1:], i+1):
                if j in processed_windows:
                    continue
                    
                # 检查是否为重复窗口：相同状态且位置相近
                if (window1[2] == window2[2] and  # 相同状态
                    window1[3] and window2[3] and  # 都有位置信息
                    abs(window1[3][0] - window2[3][0]) < 50 and  # 位置相近
                    abs(window1[3][1] - window2[3][1]) < 50):
                    group.append(window2)
                    processed_windows.add(j)
            
            if len(group) > 1:
                duplicate_groups.append(group)
        
        # 如果没有真正的重复窗口，不进行清理
        if not duplicate_groups:
            print("未发现真正的重复窗口，保持现有窗口")
            return True
        
        print(f"发现 {len(duplicate_groups)} 组重复窗口，开始清理...")
        
        # 清理重复窗口组
        for group in duplicate_groups:
            # 保留第一个窗口，关闭其他窗口
            keep_window = group[0]
            windows_to_close = group[1:]
            
            print(f"保留窗口: {keep_window[1]} (句柄: {keep_window[0]})")
            
            # 关闭重复窗口
            for hwnd, title, state, rect in windows_to_close:
                try:
                    print(f"关闭重复窗口: {title} (句柄: {hwnd})")
                    win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
                    time.sleep(0.5)
                except Exception as e:
                    print(f"关闭窗口失败: {e}")
        
        # 等待窗口关闭
        time.sleep(2)
        
        # 验证清理结果
        remaining_windows = []
        win32gui.EnumWindows(find_wechat_windows, remaining_windows)
        
        print(f"清理后剩余 {len(remaining_windows)} 个窗口")
        return True
            
    except Exception as e:
        print(f"清理重复窗口时出错: {e}")
        return False


# 窗口最大化
def maximize_wechat_window():
    """
    让企业微信窗口最大化，包括后台运行的窗口
    """
    try:
        # 查找企业微信窗口（包括后台窗口）
        def find_wechat_window(hwnd, windows):
            window_text = win32gui.GetWindowText(hwnd)
            # 排除GUI应用窗口，只查找真正的企业微信窗口
            if ("企业微信" in window_text or "WXWork" in window_text) and "自动化工具" not in window_text:
                # 检查窗口是否有效且不是最小化状态
                if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd):
                    windows.append((hwnd, window_text))
            return True
        
        windows = []
        win32gui.EnumWindows(find_wechat_window, windows)
        
        if windows:
            # 获取第一个找到的企业微信窗口
            hwnd, window_title = windows[0]
            print(f"找到企业微信窗口: {window_title}")
            
            # 检查窗口当前状态
            window_placement = win32gui.GetWindowPlacement(hwnd)
            current_state = window_placement[1]
            
            # 如果窗口是最小化状态，先恢复
            if current_state == win32con.SW_SHOWMINIMIZED:
                print("企业微信窗口当前是最小化状态，正在恢复...")
                win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)
                time.sleep(0.5)
            
            # 激活窗口
            try:
                win32gui.SetForegroundWindow(hwnd)
            except Exception as e:
                print(f"激活窗口时出现警告: {e}")
            time.sleep(0.5)  # 等待窗口激活
            
            # 最大化窗口
            win32gui.ShowWindow(hwnd, win32con.SW_MAXIMIZE)
            print("企业微信窗口已最大化")
            return True
        else:
            print("未找到企业微信窗口，尝试启动企业微信...")
            # 如果没找到窗口，尝试启动企业微信
            if check_wechat():
                print("企业微信进程正在运行，但窗口可能被隐藏")
                # 等待一段时间后重试
                time.sleep(2)
                return maximize_wechat_window()  # 递归重试
            else:
                print("企业微信未运行，正在启动...")
                start_wechat()
                time.sleep(3)  # 等待启动
                return maximize_wechat_window()  # 递归重试
            
    except Exception as e:
        print(f"最大化企业微信窗口时出错: {e}")
        return False

# 窗口管理相关函数
def find_automation_window():
    """
    查找自动化工具窗口
    """
    try:
        def find_window(hwnd, windows):
            if win32gui.IsWindow(hwnd) and win32gui.IsWindowVisible(hwnd):
                window_text = win32gui.GetWindowText(hwnd)
                # 更宽松的匹配条件，包括测试脚本窗口
                if ("企业微信自动化工具" in window_text or 
                    "WeChatAutomation" in window_text or
                    "自动化工具" in window_text or
                    "企微社群专用" in window_text or
                    "gui_app.py" in window_text or
                    "testpy" in window_text):
                    windows.append((hwnd, window_text))
                    print(f"找到可能的窗口: {window_text} (句柄: {hwnd})")
            return True
        
        windows = []
        win32gui.EnumWindows(find_window, windows)
        
        if windows:
            print(f"找到 {len(windows)} 个匹配的窗口")
            return windows[0][0]  # 返回窗口句柄
        else:
            print("未找到匹配的自动化工具窗口")
            # 列出所有可见窗口用于调试
            print("当前所有可见窗口:")
            def list_all_windows(hwnd, windows):
                if win32gui.IsWindow(hwnd) and win32gui.IsWindowVisible(hwnd):
                    window_text = win32gui.GetWindowText(hwnd)
                    if window_text:  # 只显示有标题的窗口
                        windows.append((hwnd, window_text))
                return True
            
            all_windows = []
            win32gui.EnumWindows(list_all_windows, all_windows)
            for hwnd, title in all_windows[:10]:  # 只显示前10个
                print(f"  - {title} (句柄: {hwnd})")
        return None
    except Exception as e:
        print(f"查找自动化工具窗口时出错: {e}")
        return None

def activate_automation_window():
    """
    激活自动化工具窗口到前台
    """
    try:
        # 首先尝试通过窗口标题查找
        hwnd = find_automation_window()
        if not hwnd:
            # 如果没找到，尝试通过进程ID查找
            print("通过标题未找到窗口，尝试通过进程ID查找...")
            hwnd = find_automation_window_by_pid()
        
        if hwnd:
            print(f"准备激活窗口，句柄: {hwnd}")
            
            # 获取窗口当前状态
            window_placement = win32gui.GetWindowPlacement(hwnd)
            current_state = window_placement[1]
            print(f"窗口当前状态: {current_state}")
            
            # 如果窗口是最小化状态，先恢复
            if current_state == win32con.SW_SHOWMINIMIZED:
                print("窗口被最小化，正在恢复...")
                win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)
                time.sleep(0.5)
            
            # 确保窗口可见
            if not win32gui.IsWindowVisible(hwnd):
                print("窗口不可见，正在显示...")
                win32gui.ShowWindow(hwnd, win32con.SW_SHOW)
                time.sleep(0.5)
            
            # 多次尝试激活窗口
            for attempt in range(3):
                try:
                    # 激活窗口
                    win32gui.SetForegroundWindow(hwnd)
                    time.sleep(0.2)
                    
                    # 检查是否成功激活
                    foreground_hwnd = win32gui.GetForegroundWindow()
                    if foreground_hwnd == hwnd:
                        print(f"自动化工具窗口已成功激活到前台 (尝试 {attempt + 1})")
                        return True
                    else:
                        print(f"激活失败，当前前台窗口: {win32gui.GetWindowText(foreground_hwnd)}")
                        
                except Exception as e:
                    print(f"激活尝试 {attempt + 1} 失败: {e}")
                
                time.sleep(0.5)
            
            print("所有激活尝试都失败了")
            return False
        else:
            print("未找到自动化工具窗口")
            return False
    except Exception as e:
        print(f"激活自动化工具窗口时出错: {e}")
        return False

def find_automation_window_by_pid():
    """
    通过进程ID查找自动化工具窗口
    """
    try:
        import psutil
        current_pid = os.getpid()
        print(f"当前进程ID: {current_pid}")
        
        def find_window_by_pid(hwnd, windows):
            if win32gui.IsWindow(hwnd):
                try:
                    # 获取窗口的进程ID
                    _, pid = win32api.GetWindowThreadProcessId(hwnd)
                    if pid == current_pid:
                        window_text = win32gui.GetWindowText(hwnd)
                        if window_text:  # 只返回有标题的窗口
                            windows.append((hwnd, window_text))
                            print(f"通过PID找到窗口: {window_text} (句柄: {hwnd})")
                except:
                    pass
            return True
        
        windows = []
        win32gui.EnumWindows(find_window_by_pid, windows)
        
        if windows:
            print(f"通过PID找到 {len(windows)} 个窗口")
            return windows[0][0]  # 返回第一个窗口的句柄
        else:
            print("通过PID未找到窗口")
        return None
    except Exception as e:
        print(f"通过PID查找窗口时出错: {e}")
        return None

def send_automation_window_to_back():
    """
    将自动化工具窗口发送到后台（最小化）
    """
    try:
        hwnd = find_automation_window()
        if hwnd:
            # 最小化窗口
            win32gui.ShowWindow(hwnd, win32con.SW_MINIMIZE)
            print("自动化工具窗口已最小化到后台")
            return True
        else:
            print("未找到自动化工具窗口")
            return False
    except Exception as e:
        print(f"最小化自动化工具窗口时出错: {e}")
        return False


# 从系统托盘激活企业微信到前台
def activate_wechat_from_tray():
    """
    通过进程管理激活企业微信窗口
    只使用最可靠的进程管理方法
    """
    try:
        print("正在通过进程管理激活企业微信窗口...")

        # 直接使用进程管理激活
        if activate_via_process_management():
            return True

        print("✗ 进程管理激活失败")
        return False

    except Exception as e:
        print(f"激活企业微信时出错: {e}")
        return False

def activate_via_process_management():
    """通过进程管理激活"""
    try:
        import subprocess

        # 方法1：使用更简单的PowerShell命令激活窗口
        print("使用PowerShell激活窗口...")
        powershell_cmd = '''
        try {
            $process = Get-Process -Name "WXWork" -ErrorAction SilentlyContinue | Where-Object { $_.MainWindowHandle -ne 0 } | Select-Object -First 1
            if ($process) {
                $hwnd = $process.MainWindowHandle
                Write-Host "找到企业微信窗口句柄: $hwnd"

                # 使用Windows API激活窗口
                Add-Type @"
                using System;
                using System.Runtime.InteropServices;
                public class WinAPI {
                    [DllImport("user32.dll")]
                    public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
                    [DllImport("user32.dll")]
                    public static extern bool SetForegroundWindow(IntPtr hWnd);
                    [DllImport("user32.dll")]
                    public static extern bool BringWindowToTop(IntPtr hWnd);
                }
"@
                [WinAPI]::ShowWindow($hwnd, 9)  # SW_RESTORE
                [WinAPI]::BringWindowToTop($hwnd)
                [WinAPI]::SetForegroundWindow($hwnd)
                Start-Sleep -Milliseconds 1000
                "SUCCESS"
            } else {
                "NO_PROCESS"
            }
        } catch {
            "ERROR: $_"
        }
        '''

        result = subprocess.run(
            ['powershell', '-ExecutionPolicy', 'Bypass', '-Command', powershell_cmd],
            capture_output=True,
            text=True,
            timeout=15
        )

        print(f"PowerShell输出: {result.stdout.strip()}")
        if result.stderr:
            print(f"PowerShell错误: {result.stderr.strip()}")

        if result.returncode == 0 and 'SUCCESS' in result.stdout:
            if check_window_activated():
                print("✓ 通过PowerShell Windows API成功激活！")
                return True

        # 方法2：使用VBScript激活（更兼容）
        print("尝试VBScript方法...")
        vbscript_cmd = '''
        Set WshShell = WScript.CreateObject("WScript.Shell")
        WshShell.AppActivate "企业微信"
        WScript.Sleep 1000
        '''

        with open('temp_activate.vbs', 'w', encoding='utf-8') as f:
            f.write(vbscript_cmd)

        result = subprocess.run(
            ['cscript', '//nologo', 'temp_activate.vbs'],
            capture_output=True,
            text=True,
            timeout=10
        )

        try:
            os.remove('temp_activate.vbs')
        except:
            pass

        if result.returncode == 0:
            if check_window_activated():
                print("✓ 通过VBScript成功激活！")
                return True

        # 方法3：使用tasklist查找并激活
        print("尝试tasklist方法...")
        result = subprocess.run(
            ['tasklist', '/FI', 'IMAGENAME eq WXWork.exe', '/FO', 'CSV'],
            capture_output=True,
            text=True
        )

        if 'WXWork.exe' in result.stdout:
            # 如果有进程但激活失败，尝试强制启动新实例
            print("检测到企业微信进程存在但无法激活，尝试重启...")
            try:
                subprocess.run(['taskkill', '/F', '/IM', 'WXWork.exe'], timeout=5)
                time.sleep(2)
            except:
                pass

            if start_wechat():
                time.sleep(5)  # 给更多时间启动
                if check_window_activated():
                    print("✓ 通过重启成功激活！")
                    return True

        return False

    except Exception as e:
        print(f"进程管理方法出错: {e}")
        return False



def check_window_activated():
    """检查企业微信窗口是否已经被激活（宽松检查）"""
    try:
        def find_wechat_window(hwnd, windows):
            window_text = win32gui.GetWindowText(hwnd)
            if ("企业微信" in window_text or "WXWork" in window_text) and "自动化工具" not in window_text:
                if win32gui.IsWindow(hwnd):
                    is_visible = win32gui.IsWindowVisible(hwnd)
                    is_minimized = win32gui.IsIconic(hwnd)
                    windows.append((hwnd, window_text, is_visible, is_minimized))
            return True

        windows = []
        win32gui.EnumWindows(find_wechat_window, windows)

        if windows:
            hwnd, window_title, is_visible, is_minimized = windows[0]
            print(f"找到企业微信窗口: {window_title} (句柄: {hwnd}, 可见: {is_visible}, 最小化: {is_minimized})")

            # 检查窗口是否在前台
            foreground_hwnd = win32gui.GetForegroundWindow()
            if foreground_hwnd == hwnd:
                print(f"✓ 企业微信窗口已在前台: {window_title}")
                return True
            elif is_visible and not is_minimized:
                # 窗口可见且未最小化，即使不在前台也算成功激活
                print(f"✓ 企业微信窗口已激活（可见未最小化）: {window_title}")
                return True
            else:
                print(f"⚠ 企业微信窗口存在但状态不理想: {window_title} (可见: {is_visible}, 最小化: {is_minimized})")
                return False

        print("未找到企业微信窗口")
        return False

    except Exception as e:
        print(f"检查窗口激活状态时出错: {e}")
        return False

        
            
                
                    
                        
                            
                                
                                
                                    
                                        
                                        
                                        # 安全地处理任务栏中的企业微信窗口      



def safe_activate_wechat_from_taskbar(max_attempts=3):
    """
    安全地从任务栏激活企业微信窗口，避免重复启动和黑屏问题
    支持处理托盘状态的企业微信
    max_attempts: 最大尝试次数，避免递归调用
    """
    if max_attempts <= 0:
        print("达到最大尝试次数，停止激活")
        return False

    try:
        # 首先检查企业微信进程是否正在运行
        if not check_wechat():
            print("企业微信进程未运行，启动企业微信...")
            if not start_wechat():
                print("企业微信启动失败")
                return False
            time.sleep(3)  # 等待启动

        # 查找所有企业微信窗口
        def find_wechat_windows(hwnd, windows):
            window_text = win32gui.GetWindowText(hwnd)
            if ("企业微信" in window_text or "WXWork" in window_text) and "自动化工具" not in window_text:
                if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd):
                    try:
                        window_placement = win32gui.GetWindowPlacement(hwnd)
                        current_state = window_placement[1]
                        windows.append((hwnd, window_text, current_state))
                    except Exception as e:
                        print(f"获取窗口状态失败: {e}")
                        windows.append((hwnd, window_text, None))
            return True

        windows = []
        win32gui.EnumWindows(find_wechat_windows, windows)

        if not windows:
            print("未找到企业微信窗口，使用托盘激活方法...")

            # 直接使用简洁的托盘激活方法
            if activate_wechat_from_tray():
                print("✓ 从系统托盘成功激活企业微信窗口")
                return True
            else:
                print("✗ 从托盘激活失败，尝试重新启动企业微信...")
                time.sleep(1)
                # 如果托盘激活失败，尝试重新启动
                return safe_activate_wechat_from_taskbar(max_attempts - 1)

        # 分析窗口状态
        minimized_count = len([w for w in windows if w[2] == win32con.SW_SHOWMINIMIZED])
        normal_count = len([w for w in windows if w[2] == win32con.SW_SHOWNORMAL])
        maximized_count = len([w for w in windows if w[2] == win32con.SW_SHOWMAXIMIZED])

        print(f"找到 {len(windows)} 个企业微信窗口:")
        print(f"  - 最小化: {minimized_count}")
        print(f"  - 正常: {normal_count}")
        print(f"  - 最大化: {maximized_count}")

        # 只有当真正有多个窗口时才进行清理
        if len(windows) > 1:
            print("发现多个窗口，进行智能清理...")
            cleanup_result = cleanup_duplicate_wechat_windows()
            if not cleanup_result:
                print("窗口清理失败，继续使用现有窗口")

            # 重新查找窗口
            windows = []
            win32gui.EnumWindows(find_wechat_windows, windows)
            if not windows:
                print("清理后未找到窗口，尝试重新启动...")
                if not start_wechat():
                    return False
                time.sleep(3)
                return safe_activate_wechat_from_taskbar(max_attempts - 1)

        # 现在应该只有一个窗口了，处理它
        if windows:
            hwnd, window_title, state = windows[0]
            print(f"处理窗口: {window_title} (状态: {state})")

            # 根据窗口状态进行相应处理
            if state == win32con.SW_SHOWMINIMIZED:
                print("窗口被最小化，正在恢复...")
                # 恢复窗口
                try:
                    win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)
                    time.sleep(1)

                    # 激活窗口
                    win32gui.SetForegroundWindow(hwnd)
                    time.sleep(0.5)

                    # 最大化窗口
                    win32gui.ShowWindow(hwnd, win32con.SW_MAXIMIZE)
                    print("窗口已恢复并最大化")

                except Exception as e:
                    print(f"恢复最小化窗口时出错: {e}")
                    return False

            elif state == win32con.SW_SHOWNORMAL:
                print("窗口处于正常状态，正在激活并最大化...")
                try:
                    # 激活窗口
                    win32gui.SetForegroundWindow(hwnd)
                    time.sleep(0.5)

                    # 最大化窗口
                    win32gui.ShowWindow(hwnd, win32con.SW_MAXIMIZE)
                    print("窗口已激活并最大化")

                except Exception as e:
                    print(f"激活正常状态窗口时出错: {e}")
                    return False

            elif state == win32con.SW_SHOWMAXIMIZED:
                print("窗口已经最大化，正在激活...")
                try:
                    # 只需要激活窗口
                    win32gui.SetForegroundWindow(hwnd)
                    time.sleep(0.5)
                    print("窗口已激活")

                except Exception as e:
                    print(f"激活最大化窗口时出错: {e}")
                    return False

            else:
                print(f"未知窗口状态: {state}，尝试激活...")
                try:
                    win32gui.SetForegroundWindow(hwnd)
                    time.sleep(0.5)
                    print("窗口已激活")
                except Exception as e:
                    print(f"激活未知状态窗口时出错: {e}")
                    return False

            # 验证激活是否成功
            try:
                foreground_hwnd = win32gui.GetForegroundWindow()
                if foreground_hwnd == hwnd:
                    print("窗口激活验证成功")
                    return True
                else:
                    print("窗口激活验证失败，尝试重新激活...")
                    return safe_activate_wechat_from_taskbar(max_attempts - 1)
            except Exception as e:
                print(f"验证窗口激活时出错: {e}")
                return False

        return False

    except Exception as e:
        print(f"安全激活企业微信窗口时出错: {e}")
        return False










    